﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;

namespace Editor.Tools
{
    public class GamePlayConfigExport : EditorWindow
    {
        private int totalFileCount = 0;
        private int processedFileCount = 0;
        private int successFileCount = 0;
        private int failedFileCount = 0;
        private float progress = 0;

        private bool exportBin = false;
        private bool exportClient = false;
        private bool exportServer = false;
        
        private bool isExporting = false;

        private IEnumerable<string> excels;

        private Task task;

        private bool isStyleReady = false;
        private GUIStyle m_TogStyle;
        private GUIStyle m_progressStyle;
        
        [MenuItem("Tools/GamePlayConfigExport")]
        public static void ShowWindow()
        {
            GetWindow<GamePlayConfigExport>("GamePlayConfigExport");
        }
        

        private void OnEnable()
        {
            excels = Excel2Config.GetExcelFiles(Path.Combine(Application.dataPath, Excel2Config.EXCELS_DIR));
            totalFileCount = excels.Count();
            
            
        }

        private void ReadyStyle()
        {
            if (isStyleReady)  return;
            isStyleReady = true;
            
            var togStyle = GUI.skin.GetStyle("AC Button");
            m_TogStyle = new GUIStyle(togStyle)
            {
                fixedWidth = 50
            };
            m_progressStyle = new GUIStyle(GUI.skin.label)
            {
                alignment = TextAnchor.MiddleCenter,
            };
        }

        private void OnGUI()
        {
            ReadyStyle();
            
            EditorGUILayout.HelpBox("前端导出需要选中bin和Client，后端导出需要选中Server", MessageType.Info, true);
            
            EditorGUILayout.LabelField("导出选项", EditorStyles.boldLabel);
            EditorGUILayout.BeginHorizontal();
            exportBin = GUILayout.Toggle(exportBin, "bin", m_TogStyle);
            exportClient = GUILayout.Toggle( exportClient, "Client", m_TogStyle);
            exportServer = GUILayout.Toggle( exportServer, "Server", m_TogStyle);
            EditorGUILayout.EndHorizontal();
            
            EditorGUILayout.Space(5);
            EditorGUILayout.LabelField($"文件总计:{totalFileCount}");
            
            progress = totalFileCount == 0 ? 0 : (float)processedFileCount / totalFileCount * 100;
            
            EditorGUILayout.Space(18);
            EditorGUILayout.LabelField("导出进度", EditorStyles.boldLabel);
            Rect rect = EditorGUILayout.BeginVertical();

            // EditorGUI.LabelField(rect, $"Progress: {progress}", style);
            m_progressStyle.normal.textColor = Math.Abs(progress - 100f) < 0.001f ? Color.green : Color.red;
            EditorGUI.ProgressBar(rect, progress / 100, "");
            EditorGUI.LabelField(rect, $"{processedFileCount}/{totalFileCount}", m_progressStyle);
            EditorGUILayout.Space(18);
            EditorGUILayout.EndVertical();
            
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField($"已处理:{processedFileCount}", GUILayout.Width(50));
            EditorGUILayout.LabelField($"成功:{successFileCount}", GUILayout.Width(50));
            EditorGUILayout.LabelField($"失败:{failedFileCount}", GUILayout.Width(50));
            EditorGUILayout.EndHorizontal();
            
            GUI.enabled = !isExporting;
            if (GUILayout.Button("Export") && !isExporting)
            {
                Export();
            }
            GUI.enabled = true;
        }

        private void Export()
        {
            processedFileCount = 0;
            isExporting = true;
            EditorApplication.update += Process;
        }

        private void Process()
        {
            if (!isExporting) return;

            if (processedFileCount >= totalFileCount)
            {
                isExporting = false;
                EditorApplication.update -= Process;
                return;
            }

            try
            {
                var excel = excels.ElementAt(processedFileCount);
                using var stream = File.Open(excel, FileMode.Open, FileAccess.Read);
                Excel2Config.GenerateSingleExcel(stream, exportBin, exportClient);
                ++successFileCount;
            }
            catch (Exception e)
            {
                ++failedFileCount;
                Debug.LogException(e);
            }
                        
            ++processedFileCount;
        }
    }
}